<template>
  <FormBuilder
    ref="formRef"
    :formItems="formItems"
    v-model="formData"
    :rules="rules"
  >
    <template #age="{ value }">
<!--      {} 解构出来的 value ，是子组件 slot 传递过来的参数 :value ，但它是不可改的，组件只是提供给你-->
      {{value}} 我要自己处理年龄- 年龄：{{ formData.age }}
<!--      <el-input v-model="value" type="number"></el-input>-->
    </template>
  </FormBuilder>
  <el-button @click="onSubmit">提交</el-button>
  <el-button @click="formData.age++">年龄++</el-button>
</template>

<script lang="ts" setup>
import FormBuilder from "./FormBuilder.vue"
import { computed, h, ref } from "vue"
import { FormItems } from "@/types/lowCodeForm.type"
import { FormInstance } from "element-plus"
import TestComponent from "./Test-Component.vue"
import MySelect from "./MySelect.vue"

interface IFormData {
  name: string
  age: number
  sex: number
}
const formData = ref<IFormData>({
  name: "",
  sex: 0,
  age: 0
})

const formRef = ref<FormInstance | null>(null)

async function onSubmit() {
  await formRef.value?.validate()
  console.log("校验成功, 数据源：", formData.value)
}

const sexOptions = ref([
  { label: "男", value: 0 },
  { label: "女", value: 1 }
])

const items = computed<FormItems>(() => [
  {
    label: "姓名",
    key: "name",
    type: "input",
    placeholder: "请输入姓名，输入张三可隐藏性别",
    span: 12
  },
  {
    label: "年龄",
    key: "age",
    type: "number",
    placeholder: "请输入年龄",
    onClick() {
      console.log("年龄输入框被点击了")
    },
    onInput() {
      console.log("年龄输入框输入了")
    },
    span: 12
  },
  {
    label: "性别",
    key: "sex",
    type: () => MySelect,
    props: {
      placeholder: "请选择性别",
      options: sexOptions.value // 这样写可以保证 options 响应式且不会丢失
    },
    span: 12
  },
  {
    label: "爱好",
    key: "hobbly",
    hidden: true, // 传递 true 隐藏组件
    type: () => h("div", {}, "自定义爱好组件")
  },
  {
    hidden: formData.value.name === "张三", // 根据姓名 动态隐藏
    label: "个人简介",
    key: "introduce",
    type: () => TestComponent,
    props: {
      placeholder: "请输入个人简介"
    }
  }
])

const formItems = computed<FormItems>(() =>
  items.value.filter((item) => !item.hidden)
)

const rules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" }
  ],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    { type: "number", message: "年龄必须为数字值", trigger: "blur" }
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "blur" }]
}
</script>
